import * as element from "element-plus";
import * as echarts from "echarts";

const components: { [K in string]?: any } = {};
export const npmPkgs = { echarts, element };
export const useEventsBinding = (chartConfig: any) => {
  if (!chartConfig.eventMethods) return {};
  const baseEvent: { [key: string]: any } = {};
  let clickFunStr = chartConfig.eventMethods.clickMethod;
  let mouseenterStr = chartConfig.eventMethods.mouseenterMethod;
  if (clickFunStr) {
    baseEvent["click"] = generateBaseFunc(clickFunStr, chartConfig.id);
  }
  if (mouseenterStr) {
    baseEvent["mouseenter"] = generateBaseFunc(mouseenterStr, chartConfig.id);
  }

  const lifeEvents = {};
  lifeEvents["vue:BeforeMount"] = function (e: any) {
    let beforeMountStr = chartConfig.eventMethods.beforeMountMethod;
    generateFunc(beforeMountStr, e);
  };
  lifeEvents["vue:mounted"] = function (e: any) {
    // 存储组件
    components[chartConfig.id] = e.component;
    let mountedFunStr = chartConfig.eventMethods.mountedMethod;
    generateFunc(mountedFunStr, e);
  };

  return { baseEvent, lifeEvents };
};

export function generateBaseFunc(fnStr: string, id: string) {
  try {
    return new Function(`return ${fnStr}`)().bind(undefined, components, id);
  } catch (error) {
    console.error(error);
  }
}

export function generateFilterFunc(fnStr: string, data: any, res: any) {
  try {
    return new Function(`return ${fnStr}`)().bind(undefined, data, res);
  } catch (error) {
    console.error(error);
  }
}

function generateFunc(fnStr: string, e: any) {
  try {
    Function(`
        "use strict";
      return ${fnStr}`)().bind(e?.component)(e, components, npmPkgs);
  } catch (error) {
    console.error(error);
  }
}
